package com.act;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.Enum.FriendsApplyState;
import com.bean.BaseBean;
import com.bean.Friend;
import com.bean.FriendApplyList;
import com.common.Constant;
import com.common.LocalFileHelper;
import com.common.TextHttpResponseHandler;
import com.mUI.XListView;
import com.mUI.XListView.IXListViewListener;
import com.xike.kyt.R;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class Friend_NewAct extends BaseAct {

	TextView tv_back;
	XListView listView;
	FriendApplyList friendList;
	MyAdapter adapter;

	ArrayList<Friend> allpys = new ArrayList<Friend>();

	int pageCursor = 1;
	boolean isRefresh = false;
	boolean isLoadingMore = false;
	boolean hasAgree = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_friend_new);
		initViews();
	}

	@Override
	protected void initViews() {
		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		tv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (hasAgree) {
					setResult(1);
				}
				finish();
			}
		});
		listView = (XListView) findViewById(R.id.friendNew_listView);
		listView.setPullRefreshEnable(true);
		listView.setPullLoadEnable(true);
		listView.setAutoLoadEnable(true);

		listView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pageCursor = 1;
				isRefresh = true;
				serviceGetNewFrinds();
			}

			@Override
			public void onLoadMore() {
				pageCursor++;
				isLoadingMore = true;
				serviceGetNewFrinds();
			}
		});

		adapter = new MyAdapter();
		listView.setAdapter(adapter);

		serviceGetNewFrinds();
		// serviceTest();

	}

	@Override
	protected void updateViews() {
		ArrayList<Friend> loadApplys = friendList.getApplys();
		if (loadApplys != null && loadApplys.size() > 0) {

			if (isRefresh) {
				allpys.clear();
				allpys.addAll(loadApplys);
				adapter.notifyDataSetChanged();
				isRefresh = false;
				listView.stopRefresh();
				listView.updateRefreshTime();
				listView.setPullLoadEnable(true);
			} else {
				allpys.addAll(loadApplys);
				adapter.notifyDataSetChanged();
				if (isLoadingMore) {
					listView.stopLoadMore();
				}
				if (friendList.getNext_cursor() > 0) {
					listView.showFooterView();
				} else {
					listView.setPullLoadEnable(false);
				}
			}
		}
	}

	private void serviceGetNewFrinds() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_FRIEND_NEW, params);
		// // 本地缓存
		// if (LocalFileHelper.getInstance(this).fileIsExited(strUrl) && !isRefresh) {
		// FriendApplyList result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), FriendApplyList.class);
		// dealRequestResult(result);
		// return;
		// }

		client.get(this, strUrl, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				FriendApplyList result = gson.fromJson(responseString, FriendApplyList.class);
				dealRequestResult(result);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				if (isRefresh) {
					listView.stopRefresh();
				}
				mToast.showToast(Friend_NewAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(FriendApplyList result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				friendList = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
				if (isRefresh) {
					listView.stopRefresh();
				}
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
			if (isRefresh) {
				listView.stopRefresh();
			}
		}
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return allpys.size();
		}

		@Override
		public Friend getItem(int position) {
			return allpys.get(position);
		}

		@Override
		public long getItemId(int position) {
			return allpys.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = View.inflate(Friend_NewAct.this, R.layout.listitem_friend_new, null);
				holder = new ViewHolder();
				holder.tv_desc = (TextView) convertView.findViewById(R.id.lvitem_friendNew_tv_desc);
				holder.tv_name = (TextView) convertView.findViewById(R.id.lvitem_friendNew_tv_name);
				holder.tv_status = (TextView) convertView.findViewById(R.id.lvitem_friendNew_tv_status);
				holder.img_avator = (ImageView) convertView.findViewById(R.id.lvitem_friendNew_img_avator);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();

			}

			Friend apply = getItem(position);

			BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
			MyUtil.displayImageView(Friend_NewAct.this, apply.getAvator(), holder.img_avator, bd.getBitmap(), false);

			MyUtil.setTextViewText(holder.tv_name, apply.getNick_name(), 0, "未知用户");

			if (apply.getStatus() == FriendsApplyState.Applied.getIntValue()) {
				holder.tv_status.setText("接受");
				holder.tv_status.setBackgroundResource(R.drawable.corner_06bf04);
				holder.tv_status.setTextColor(Color.WHITE);
				holder.tv_status.setTag(apply.getId());
				holder.tv_status.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						serviceFriendAgree((TextView) v);
					}
				});
				holder.tv_status.setVisibility(View.VISIBLE);
				MyUtil.setTextViewText(holder.tv_desc, apply.getInfo(), View.GONE, "");

			} else if (apply.getStatus() == FriendsApplyState.Agreed.getIntValue()) {
				holder.tv_status.setText("已接受");
				holder.tv_status.setBackgroundColor(Color.WHITE);
				holder.tv_status.setTextColor(Color.parseColor("#999999"));
				holder.tv_status.setVisibility(View.VISIBLE);
				MyUtil.setTextViewText(holder.tv_desc, StringUtil.isNotNull(apply.getSummary()) ? apply.getSummary() : apply.getInfo(), View.GONE, "");
			} else {
				holder.tv_status.setVisibility(View.INVISIBLE);
			}

			return convertView;
		}

	}

	private static class ViewHolder {
		TextView tv_name;
		TextView tv_desc;
		ImageView img_avator;
		TextView tv_status;
	}

	private void serviceFriendAgree(final TextView tv_status) {

		// tv_status.setBackgroundColor(Color.WHITE);
		// tv_status.setTextColor(Color.parseColor("#828282"));
		// tv_status.setOnClickListener(null);
		// tv_status.setText("已接受");

		long applyId = (Long) tv_status.getTag();

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(applyId)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_FRIENDS_AGREE, params);
		// 网络请求
		client.put(strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					// 同意成功
					tv_status.setBackgroundColor(Color.WHITE);
					tv_status.setTextColor(Color.parseColor("#828282"));
					tv_status.setOnClickListener(null);
					tv_status.setText("已接受");
					hasAgree = true;
				} else {
					mToast.showToast(Friend_NewAct.this, getResources().getString(R.string.net_error));
				}

				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Friend_NewAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

}
